import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'
import store from '@/store'
// create an axios instance
// 设置时间
const timeout = 36000
function isCheckTimeOut() {
  // 是否超时
// 超时逻辑  (当前时间  - 缓存中的时间) 是否大于 时间差
  return (Date.now() - store.getters.hrsaasTime) / 1000 > timeout
}
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use((config) => {
  if (store.getters.token) {
    console.log(isCheckTimeOut())
    if (isCheckTimeOut()) { // 超时
      // store.dispatch('user/logout')登出操作
      router.push('/login')// 跳转到登录页面
      return Promise.reject(new Error('接口超时'))// 提示登录超时
    }
    // 注入token
    config.headers['Authorization'] = store.getters.token
  }
  console.log(config)
  return config
}, error => {
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use(
  (response) => {
  // console.log(response)
    return response.data
  }, (err) => {
    Message.error(err.msg)
    return Promise.reject(err)
  }
)

export default service
